package org.example.mq.product;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.UUID;

public class RocketMQProducer {
    // 生产者组名
    private static final String PRODUCER_GROUP = "TEST_IDEMPOTENT_GROUP";
    // NameServer地址
    private static final String NAME_SERVER_ADDR = "localhost:9876";
    // 主题名
    private static final String TOPIC = "TEST_IDEMPOTENT_TOPIC";
    // 标签
    private static final String TAG = "tag";

    public static void main(String[] args) throws MQClientException, InterruptedException {
        // 实例化消息生产者
        DefaultMQProducer producer = new DefaultMQProducer(PRODUCER_GROUP);

        // 设置NameServer地址
        producer.setNamesrvAddr(NAME_SERVER_ADDR);

        // 启动生产者
        producer.start();
        System.out.println("生产者启动成功");
        // 设置消息唯一ID
        String messageId = UUID.randomUUID().toString();

        try {
            for (int i = 0; i < 10; i++) {
                // 创建消息内容
                String messageContent = "业务内容 " + i;
                // 使用原生RocketMQ的Message类创建消息
                Message message = new Message(
                        TOPIC,                  // 主题
                        TAG,                    // 标签
                        messageContent.getBytes(RemotingHelper.DEFAULT_CHARSET)  // 消息体
                );

                // 设置消息唯一ID
//                messageId = UUID.randomUUID().toString();
                message.putUserProperty("messageId", messageId);
                // 发送消息
                SendResult sendResult = producer.send(message);

                // 打印发送结果
                System.out.printf("发送结果: %s, 消息ID: %s%n", sendResult, messageId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(1000);
        }

        // 关闭生产者
        producer.shutdown();
        System.out.println("生产者已关闭");
    }
}
